import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:5000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    // 如果是上传文件的请求，设置正确的Content-Type
    if (config.url === '/user/avatar' && config.method === 'post') {
      // 删除Content-Type，让浏览器自动设置multipart/form-data
      delete config.headers['Content-Type'];
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期或无效，清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('isLoggedIn')
      // 跳转到登录页
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

// 认证API服务
export const authAPI = {
  // 用户登录
  login: async (username, password) => {
    try {
      const response = await api.post('/login', {
        username,
        password
      })
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 验证token
  verifyToken: async () => {
    try {
      const response = await api.get('/verify-token')
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 检查登录状态
  checkLoginStatus: () => {
    const token = localStorage.getItem('token')
    const isLoggedIn = localStorage.getItem('isLoggedIn')
    return !!(token && isLoggedIn === 'true')
  },

  // 获取当前用户信息
  getCurrentUser: () => {
    return {
      username: localStorage.getItem('username'),
      token: localStorage.getItem('token')
    }
  },

  // 退出登录
  logout: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('isLoggedIn')
  },

  // 获取用户个人信息
  getUserProfile: async () => {
    try {
      const response = await api.get('/user/profile')
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 更新用户个人信息
  updateUserProfile: async (userData) => {
    try {
      const response = await api.put('/user/profile', userData)
      return response.data
    } catch (error) {
      throw error
    }
  },

  // 上传用户头像
  uploadAvatar: async (file) => {
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      
      const response = await api.post('/user/avatar', formData);
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 删除用户头像
  deleteAvatar: async () => {
    try {
      const response = await api.delete('/user/avatar');
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 修改密码
  changePassword: async (passwordData) => {
    try {
      const response = await api.put('/user/password', passwordData)
      return response.data
    } catch (error) {
      throw error
    }
  }
}

export default api